/**
 * @this
 *
 * @flow
 */

'use strict'
import React, {Component} from 'react'
import {
  StyleSheet,
  View,
  Text,
  Button,
  FlatList,
  Keyboard,
  TouchableOpacity,
} from 'react-native'

import store from 'react-native-rxstorage'
import * as DevUtil from '../../app/commons/utils/devEnv'

export const devEnvironmentList = [
  {
    betaName: '自定义',
    baseUrl: '',
  },
  {
    betaName: 'betaC',
    baseUrl: 'http://wxoc3.mubiyixia.nat300.top',
  },
  {
    betaName: '测试环境',
    baseUrl: 'http://wxoc5.mubiyixia.nat300.top',
  },
  {
    betaName: '外网测试环境',
    baseUrl: 'http://appuat.666.nat300.top',
  },
  {
    betaName: '开发环境',
    baseUrl: 'http://wxoc48.666.nat300.top',
  },
]

export default class SwithDns extends Component {
  static navigationOptions = (a, b) => {
    b = b || {}
    const route = b.route || {}
    const right = () => {
      return (
        <Button
          title={'保存'}
          onPress={e => {
            const p = route.params || {}
            const save = p.save || null
            save && save()
          }}
        />
      )
    }
    return {
      headerTitle: '切换域名地址',
      headerRight: right,
    }
  }

  constructor(props) {
    super(props)
    this.state = {
      currentValue: '',

      selectIndex: -1,
      selectTitle: '',
      selectValue: '',

      diyValue: '',
    }
  }

  componentDidMount() {
    this.props.navigation.setParams({
      save: this._save,
    })

    this.getUrl()
  }

  getUrl = () => {
    DevUtil.getDevBaseUrl().then(baseUrl => {
      this.setState({currentValue: baseUrl})
    })

    this.getDiyUrl().then(url => {
      console.log('diyValue=' + url)
      this.setState({diyValue: url})
    })
  }

  editSucc = () => {
    this.getUrl()
    this.setState({selectIndex: 0})
  }

  async getDiyUrl() {
    return await store.get('diyUrl')
  }

  _save = () => {
    const {selectIndex, selectValue, diyValue} = this.state
    if (selectIndex < 0) {
      alert('没有更改')
      return
    }

    const url = selectIndex === 0 ? diyValue : selectValue

    DevUtil.setDevBaseUrl(url)
    this.getUrl()
    alert('修改成功，需要重启app')
  }

  _renderItem = data => {
    const {item, index} = data
    const {diyValue, selectIndex} = this.state

    const betaName = item.betaName
    const baseUrl = index === 0 ? diyValue : item.baseUrl
    const bg = index === selectIndex ? {backgroundColor: '#FFA500'} : {}
    return (
      <TouchableOpacity
        style={[styles.listBtn, bg]}
        onPress={() => {
          Keyboard.dismiss()
          this.setState({
            selectIndex: index,
            selectTitle: betaName,
            selectValue: baseUrl,
          })
        }}>
        <Text style={styles.text}>{betaName}</Text>
        <Text style={styles.text}>{baseUrl}</Text>
      </TouchableOpacity>
    )
  }

  render() {
    const {currentValue, selectTitle, selectValue} = this.state

    return (
      <View style={styles.container}>
        <View style={styles.selView}>
          <Text style={styles.selText}>当前-使用的`域名`</Text>
          <Text>{currentValue}</Text>
          <Text style={[styles.selText, {marginTop: 10}]}>当前-选择的`域名`</Text>
          <View style={{flexDirection: 'row', alignItems: 'center'}}>
            <Text>{selectTitle}</Text>
            <TouchableOpacity
              style={styles.selTouch}
              onPress={() => {
                const params = {
                  url: selectValue,
                  title: '编辑-' + selectTitle,
                  callback: this.editSucc,
                }
                this.props.navigation.navigate('EditSwithDns', params)
              }}>
              <Text style={styles.selTouchTxt}>编辑</Text>
            </TouchableOpacity>
          </View>
          <Text>{selectValue}</Text>
        </View>
        <View style={{height: 1, backgroundColor: '#00FFFF'}} />
        <FlatList
          style={{flex: 1}}
          data={devEnvironmentList}
          keyExtractor={(item, index) => index}
          numColumns={1}
          horizontal={false}
          // ListEmptyComponent={this._renderEmpty}
          renderItem={this._renderItem}
          // ItemSeparatorComponent={this._renderSeparator}
          onEndReachedThreshold={0.5}
          showsVerticalScrollIndicator={false}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  selView: {
    padding: 5,
  },
  selText: {
    fontSize: 20,
  },
  selTouch: {
    marginLeft: 10,
    width: 80,
    height: 20,
    backgroundColor: 'blue',
    borderRadius: 3,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selTouchTxt: {
    color: 'white',
  },
  button: {
    padding: 20,
    backgroundColor: 'blue',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    lineHeight: 20,
    fontSize: 12,
    color: 'white',
  },
  listBtn: {
    marginHorizontal: 30,
    marginVertical: 10,
    borderRadius: 3,
    backgroundColor: '#008B8B',
    justifyContent: 'center',
    alignItems: 'center',
  },
})
